package com.seecen.cywbackend.controller;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.seecen.cywbackend.utils.FileUtil;
import com.seecen.cywbackend.utils.Result;
import com.seecen.cywbackend.utils.ResultCodeEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/file")
public class FileController {

    @Resource
    private FileUtil fileUtil;

    @PostMapping("/imgUpload")
    public Result imgUpload(@RequestParam("file") MultipartFile file) {
        // 校验文件大小
        if (file.getSize() > 5 * 1024 * 1024) { // 限制为 5MB
            log.warn("文件大小超出限制，文件名: {}", file.getOriginalFilename());
            return Result.build(null, ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
        // 校验文件名并生成安全文件名
        String sanitizedFileName;
        try {
            sanitizedFileName = sanitizeFileName(file.getOriginalFilename());
        } catch (IllegalArgumentException e) {
            log.warn("文件名不合法: {}", file.getOriginalFilename());
            return Result.build(null, ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
        // 上传文件
        try (InputStream inputStream = file.getInputStream()) {
            String url = fileUtil.uploadFileAndGetPermanentUrl(inputStream, sanitizedFileName);
            if (StringUtils.isNotBlank(url)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("url", url);
                return Result.ok(jsonObject);
            } else {
                log.error("上传文件失败：返回的URL为空，文件名: {}", sanitizedFileName);
                return Result.build(null,ResultCodeEnum.FILE_UPLOAD_ERROR);
            }
        } catch (Exception e) {
            log.error("上传文件异常，文件名: {}", file.getOriginalFilename(), e);
            return Result.build(null,ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    /**
     * 校验并清理文件名
     */
    private String sanitizeFileName(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return UUID.randomUUID().toString(); // 默认文件名
        }
        // 过滤非法字符
        String sanitized = fileName.replaceAll("[^a-zA-Z0-9.-]", "_");
        // 校验文件扩展名
        String[] allowedExtensions = {".jpg", ".jpeg", ".png", ".gif"};
        for (String ext : allowedExtensions) {
            if (sanitized.toLowerCase().endsWith(ext)) {
                return sanitized;
            }
        }
        throw new IllegalArgumentException("不支持的文件类型");
    }
}
